<script setup lang="ts">
import { reqPath } from '@/api/reqPath';
import { IconDownload, IconError, IconSuccess, IconRemind } from '@computing/opendesign-icons';
import { downloadFileWithResponse } from '@/utils/common-service';
import { traduction, getErrorTranslate } from '@/utils/language';
import { showElMessage } from '@/utils/utils';
import { computed, onMounted, onUnmounted, ref, reactive, Ref } from 'vue';
import useStore from '@/stores';
import {
  downloadData,
  editSystemDiagnostic,
  getDownloadProgress,
  getDownloadUrl,
  processor,
  systemDiagnostic,
  getPCIeCard,
} from './systemlog.server';
import { parsingInfo } from './systemlogFunctons';
import { showFailedMessage } from '@/utils/composition';

import Loading from '@/components/Loading/Loading.vue';
import GlobalStoreService from '@/services/gloabal-store-service';
import Dialog from '@/components/Dialog/Dialog.vue';
import { getStoreData } from '@/utils/composition';
import { hostItemT } from '@/model/Maintance/systemlog-interface';
import type { CheckboxValueType } from 'element-plus';

const npuTypeDialogRef = ref();
const checkAll = ref(false);
const isIndeterminate = ref(false);
const npuType = ref([] as any);
const npuSupportedPartNumber = ['03029WRV', '03028DFH', '0302018194', '0302034997', '06030667'];
const npuTypeList = [
  {
    id: 0,
    value: 'Blackbox',
    label: traduction('NPU_OPTION_BLACKBOX'),
  },
  {
    id: 1,
    value: 'Device',
    label: traduction('NPU_OPTION_DEVICE'),
  },
];

const handleCheckAllChange = (val: CheckboxValueType) => {
  if (val) {
    npuType.value = ['Blackbox', 'Device'];
    npuTypeDialogRef.value.enable();
  } else {
    npuType.value = [];
    npuTypeDialogRef.value.disable();
  }
  isIndeterminate.value = false;
};

const handleCheckTypeChange = (value: CheckboxValueType[]) => {
  if (value.length === 0) {
    npuTypeDialogRef.value.disable();
  } else {
    npuTypeDialogRef.value.enable();
  }
  const checkedCount = value.length;
  checkAll.value = checkedCount === npuTypeList.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < npuTypeList.length;
};

const globalStoreService = new GlobalStoreService();
const errorMsg = traduction('COMMON_FAILED');
const dialogRef = ref();
const npuSelectItem = ref({} as any);
const npuDialogRef = ref();
const dialogConfig = reactive({
  id: 'SDIBlackBoxTip',
  type: 'warning',
  content: '',
  title: traduction('COMMON_CONFIRM'),
});
const multihost = computed(() => getStoreData('loct', 'multihost'));

const percentValue = ref(0);
const percent = ref('0%');
const npuDialogConfig = reactive({
  id: 'NPUBoxTip',
  type: 'warning',
  content: '',
  title: traduction('COMMON_CONFIRM'),
});
const npuTypeDialogConfig = reactive({
  id: 'NPUTypeTip',
  type: 'warning',
  content: '',
  title: traduction('COMMON_DOWN'),
  okButton: { id: 'npu_type_download_button', label: traduction('COMMON_DOWN') },
  cancelButton: { id: 'npu_type_cancel_button' }
});
let timer: any[] = [];

let isSecondEntry: boolean = false;
let hostSecondEntry = false;

let npuLogProgressItem: any = {};
const str = sessionStorage.getItem('npuLogProgressItem');
if (str) {
  npuLogProgressItem = JSON.parse(str);
}
let hostLogProgressUrl: any = sessionStorage.getItem('hostLogProgressUrl');
let hostLogProgressItem: any = {};
const str1 = sessionStorage.getItem('hostLogProgressItem');
if (str1) {
  hostLogProgressItem = JSON.parse(str1);
}
const store = useStore();
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const fdmSupport = computed(() => getStoreData('loct', 'fdmspt'));
// systemInfo第二个待判断产品类型更换desc描述
let systemInfo = reactive([
  {
    id: 'blackBox',
    title: traduction('SYSTEM_LOG_BLACKCLIP'),
    idPCIe: 'blackBoxPCIe',
    titlePCIe: traduction('SYSTEM_LOG_PCIE'),
    statusPCIe: false,
    disable: false,
    desc: traduction('SYSTEM_LOG_BLACKCLIP1'),
    status: false,
    fileName: 'blackbox.tar',
    size: '4M',
    down: false,
    idSDIBlackBox: 'SDIBlackBox',
    titleSDIBlackBox: traduction('SYSTEM_LOG_SDI'),
    descSDIBlackBox: traduction('SYSTEM_LOG_PCIE_SID'),
    statusSDIBlackBox: false,
    fileNameSDIBlackBox: 'SmartNIC_blackbox.tar',
    sizeSDIBlackBox: '60K',
    downSDIBlackBox: false,
    currentDownType: '',
    show: !multihost.value,
  },
  {
    show: !multihost.value,
    id: 'serialPort',
    title: traduction('SYSTEM_LOG_SERIAL_PORT'),
    desc: traduction('SYSTEM_LOG_SERIAL_PORT1_TIP'),
    status: false,
    fileName: 'systemcom.tar',
    size: '2M',
    down: false,
    disable: false,
  },
]);

let npuCards: any[] = reactive([]);
let hostLogCards: Ref<hostItemT[]> = ref([]);

// 获取host集合数据
function getAllHostLog() {
  hostLogCards.value.splice(0);
  let arr = [];
  for (let i = 1; i <= 8; i++) {
    arr.push({
      title: `system${i}com.tar`,
      id: 'HOST',
      progressResult: '',
      isCollectingOk: false,
      isCollectingErr: false,
      showProgress: false,
      down: false,
      fileName: `system${i}com.tar`,
      systemId: `${i}`,
      hostPercent: '0%',
      hostPercentValue: 0,
    });
  }
  hostLogCards.value = arr;
}

// 获取处理器集合数据
function getAllProcessor() {
  npuCards.splice(0);
  Promise.all([processor(), getPCIeCard()])
    .then(res => {
      const moduleResp = res[0] as any;
      const moduleNPU = parsingInfo((moduleResp.NPU ?? []).filter((npu :any) => npu.State !== 'Absent'));
      const cardBody = res[1];
      let cardNPU = [] as any[];
      if (cardBody && Array.isArray(cardBody)) {
        const adaptedRes = cardBody
          .filter(
            item =>
              ['NPU'].some(itemTemp =>
                (item.FunctionType as string)?.toUpperCase().includes(itemTemp)
              ) && npuSupportedPartNumber.includes(item.PartNumber)
          )
          .map(item => {
            const match = (item.Id as string).match(/\d+/) as any;
            const slotNumber = parseInt(match[0], 10);
            return isNaN(slotNumber)
              ? null
              : {
                  slotNumber,
                  ...item
                };
          });
        cardNPU = parsingInfo(adaptedRes) as any[];
      }
      npuCards.push(...moduleNPU, ...cardNPU);
      const npuArr = sessionStorage.getItem('npuLogProgressItem');
      if (npuArr) {
        const targetArr = JSON.parse(npuArr);
        isSecondEntry = true;
        const npuCardsMap = npuCards.reduce((map, npu) => {
            map[npu.title] = npu;
            return map;
        }, {});
        targetArr.forEach((target: any) => {
          const targetItem = npuCardsMap[target.title];
          if (targetItem) {
            taskService(target.url, targetItem);
          }
        });
      }
      globalStoreService.setValue('isLoading', false);
    })
    .catch(() => {
      globalStoreService.setValue('isLoading', false);
    });
}

// 进度条结尾部分的展示
const progressFormat = (value: number) => {
  return '';
};

// 黑匣子功能 / 系统串口数据记录功能 开关发生修改
function change(item: any) {
  const par = {};
  if (item.id === 'blackBox') {
    par['BlackBoxEnabled'] = item.status;
  } else if (item.id === 'serialPort') {
    par['SerialPortDataEnabled'] = item.status;
  }
  editSystemDiagnostic(par)
    .then(() => {
      showElMessage('success', traduction('COMMON_SUCCESS'));
    })
    .catch(() => {
      item.status = !item.status;
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}

// PCIe接口 开关发生修改
function changePCIe(item: any) {
  editSystemDiagnostic({
    PCIeInterfaceEnabled: item.statusPCIe,
  })
    .then(() => {
      if (item.statusPCIe) {
        item.disable = false;
      } else {
        item.disable = true;
        item.status = false;
      }
      showElMessage('success', traduction('SYSTEM_LOG_PCIE_TIP'));
    })
    .catch(() => {
      item.statusPCIe = !item.statusPCIe;
      showElMessage('error', traduction('COMMON_FAILED'));
    });
}

// 点击下载 获取下载地址
function download(item: any) {
  const id = item.id;
  if (id === 'NPU') {
    npuTypeDialogRef.value.show();
    initNPUType();
    npuSelectItem.value = item;
    return;
  }
 
  if (item.status) {
    if (item.down) {
      return;
    }
    item.down = true;
    let url = '';
    let npuId = 0;
    if (id === 'blackBox') {
      url = reqPath.maintance.systemlog.downloadBlackBox;
      item.currentDownType = 'blackBox';
    } else if (id === 'serialPort') {
      url = reqPath.maintance.systemlog.downloadSerialPortData;
    }
    getDownloadUrl(url, {})
      .then((data: any) => {
        taskService(data.url, item);
      })
      .catch(() => {
        item.down = false;
      });
  } else {
    if (id === 'blackBox') {
      showElMessage('error', traduction('SYSTEM_LOG_BLACKCLIP_MEG'));
    } else if (id === 'serialPort') {
      showElMessage('error', traduction('SYSTEM_LOG_SERIAL_PORT_MEG'));
    }
  }
}

function initNPUType() {
  npuTypeDialogRef.value.disable();
  npuType.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
}

// SDI点击下载 获取下载地址
function sdiDownload(item: any) {
  if (item.statusSDIBlackBox) {
    if (item.downSDIBlackBox) {
      return;
    }
    dialogRef.value.show();
  } else {
    showElMessage('error', traduction('REMOTE_FULL_TIP_NOT_SUPPORT'));
  }
}

function closeModal(reason: boolean) {
  if (reason) {
    dialogRef.value.hide();
    systemInfo[0].downSDIBlackBox = true;
    getDownloadUrl(reqPath.maintance.systemlog.downloadSDIBlackBox, {})
      .then((data: any) => {
        systemInfo[0].currentDownType = 'sdiBlackBox';
        if (!data.url || data.url === '') {
          showElMessage('error', traduction('COMMON_FAILED'));
          systemInfo[0].downSDIBlackBox = false;
        } else {
          taskService(data.url, systemInfo[0]);
        }
      })
      .catch(() => {
        systemInfo[0].downSDIBlackBox = false;
      });
  } else {
    dialogRef.value.hide();
  }
}
function hostLogDownload(item: hostItemT) {
  if (item.down) {
    return;
  }
  item.down = true;
  let url = reqPath.maintance.systemlog.downloadSerialPortData;
  getDownloadUrl(url, { SystemId: item.systemId })
    .then((data: any) => {
      item.showProgress = true;
      sessionStorage.setItem('hostLogProgressUrl', data.url);
      sessionStorage.setItem('hostLogProgressItem', JSON.stringify(item));
      taskService(data.url, item);
    })
    .catch(err => {
      const errorCode = err?.data?.error?.[0]?.code;
      if (errorCode) {
        showFailedMessage(getErrorTranslate(errorCode));
      } else {
        showElMessage('error', errorMsg);
      }
      item.down = false;
    });
}
function closeNPUTypeModal(reason: boolean) {
  if (reason) {
    npuDialogRef.value.show();
  }
  npuTypeDialogRef.value.disable();
  npuTypeDialogRef.value.hide();
}
function closeNPUModal(reason: boolean) {
  if (reason) {
    npuDialogRef.value.hide();
    let item = {} as any;
    npuCards.forEach(npu => {
      if (npu.title === npuSelectItem.value.title) {
        item = npu;
      }
    });
    if (item.status) {
      if (item.down) {
        return;
      }
      item.down = true;
      let npuId: number = getParams(item);
      const url = `/UI/Rest/Maintenance/SystemDiagnostic/DownloadNPUDeviceLog`;
      const params = { NpuId: npuId, LogType: npuType.value };
      getDownloadUrl(url, params)
        .then((data: any) => {
          item.showProgress = true;
          item.url = data.url;
          if (sessionStorage.getItem('npuLogProgressItem')) {
            const targetArr = JSON.parse(sessionStorage.getItem('npuLogProgressItem') as string) ?? [];
            targetArr.push(item);
            sessionStorage.setItem('npuLogProgressItem', JSON.stringify(targetArr));
          } else {
            sessionStorage.setItem('npuLogProgressItem', JSON.stringify([item]));
          }
          taskService(data.url, item);
        })
        .catch(err => {
          const errorCode = err?.data?.error?.[0]?.code;
          if (errorCode) {
            showFailedMessage(getErrorTranslate(errorCode));
          } else {
            showElMessage('error', errorMsg);
          }
          item.down = false;
        });
    }
  } else {
    npuDialogRef.value.hide();
  }
}

// 开始下载
function beginDownLoad(item: any) {
  let tempFileName = '';
  if (item.currentDownType === 'sdiBlackBox') {
    tempFileName = item.fileNameSDIBlackBox;
  } else {
    tempFileName = item.fileName;
  }
  downloadData(tempFileName)
    .then((res: any) => {
      const fileName = res.headers['content-disposition'].split('=')[1];
      downloadFileWithResponse(res.data, fileName);
      if (item.currentDownType === 'sdiBlackBox') {
        item.downSDIBlackBox = false;
      } else {
        item.down = false;
      }
      showElMessage('success', traduction('DOWNLOAD_SUCCESS'));
    })
    .catch(() => {
      if (item.currentDownType === 'sdiBlackBox') {
        item.downSDIBlackBox = false;
      } else {
        item.down = false;
      }
      showElMessage('error', traduction('DOWNLOAD_FAILED'));
    });
}

function getParams(item: any) {
  const pattern_multi = /^NPU\d+-\d+$/;
  const pattern_single = /^NPU\d+$/;
  const pattern_card = /^(NPU Card )\d+$/;
  let npuId: number = 0;
  item.fileName = 'npu_device_log.tar.gz';
  if (pattern_multi.test(item.title)) {
    npuId =
    ((Number(item.title.slice(3).split('-')[0]) - 1) * 2) +
    Number(item.title.slice(3).split('-')[1]);
  } else if (pattern_single.test(item.title)) {
    const match = item.title.match(/^(?<npuId>NPU\d+)$/);
    npuId = Number(match.groups.npuId.slice(3));
    item.fileName = `npu${npuId}_device_log.tar.gz`;
  } else if (pattern_card.test(item.title)) {
    npuId = parseInt(((item.title as string).match(/\d+/) as any[])[0], 10);
    npuId = (npuId * 2) - 1; 
  } else {}
  return npuId;
}

function setPercent(data: any, id: string, item: any) {
  if (id === 'NPU') {
    item.percent = data.prepare_progress ? data.prepare_progress + '%' : '0%';
    item.percentValue = data.prepare_progress;
  }
}
function setTaskStatus(item: any) {
  item.isCollectingOk = true;
  item.progressResult = 'success';
  if (item.id === 'NPU') {
    clearTask(item);
    if (isSecondEntry) {
      let cur = npuCards.find(npu => npu.title === item.title);
      if (cur) {
        cur.isCollectingOk = true;
        clearTask(cur);
      }
    }
  }
  if (item.id === 'HOST') {
    clearHostTask(item);
    if (hostSecondEntry) {
      let cur = hostLogCards.value.find(host => host.title === item.title);
      if (cur) {
        cur.isCollectingOk = true;
        clearHostTask(cur);
      }
    }
  }
}
function setErr(item: any) {
  item.isCollectingErr = true;
  item.progressResult = 'warning';
  if (item.id === 'NPU') {
    clearTask(item);
    if (isSecondEntry) {
      let cur = npuCards.find(npu => npu.title === item.title);
      if (cur) {
        cur.isCollectingErr = true;
        clearTask(cur);
      }
    }
  }
  if (item.id === 'HOST') {
    clearHostTask(item);
    if (hostSecondEntry) {
      let cur = hostLogCards.value.find(host => host.title === item.title);
      if (cur) {
        cur.isCollectingErr = true;
        clearHostTask(cur);
      }
    }
  }
}
function setCatch(item: any, err: { data: any }) {
  item.isCollectingErr = true;
  item.progressResult = 'warning';
  setErr(item);
  const errorCode = err?.data?.error?.[0]?.code;
  if (errorCode) {
    showFailedMessage(getErrorTranslate(errorCode));
  } else {
    showElMessage('error', errorMsg);
  }
}
// 获取下载进度等
function taskService(url: string, item: any) {
  getDownloadProgress(url)
    .then((data: any) => {
      if (item.id === 'HOST') {
        item.hostPercent = data.prepare_progress ? data.prepare_progress + '%' : '0%';
        item.hostPercentValue = data.prepare_progress;
      }
      setPercent(data, item.id, item);
      if (data.prepare_progress === 100 && data.state === 'Completed') {
        setTaskStatus(item);
        beginDownLoad(item);
      } else if (data.prepare_progress === null && data.state === 'Exception') {
        if (item.currentDownType === 'sdiBlackBox') {
          item.downSDIBlackBox = false;
        }
        setErr(item);
        showElMessage('error', traduction('COMMON_FAILED'));
        return;
      } else {
        const timerItem = setTimeout(() => {
          taskService(url, item);
        }, 500);
        timer.push(timerItem);
      }
    })
    .catch((err: any) => {
      setCatch(item, err);
      item.down = false;
    });
}
// 清除下载状态
function clearHostTask(item: any) {
  sessionStorage.removeItem('hostLogProgressItem');
  sessionStorage.removeItem('hostLogProgressUrl');
  const timerItem = setTimeout(() => {
    item.hostPercentValue = 0;
    item.hostPercent = '0%';
    item.showProgress = false;
    item.isCollectingOk = false;
    item.isCollectingErr = false;
    item.down = false;
    item.progressResult = '';
  }, 3000);
  timer.push(timerItem);
}
// 清除下载状态
function clearTask(item: any) {
  const targetItem = sessionStorage.getItem('npuLogProgressItem');
  if (targetItem) {
    const targetArr = JSON.parse(targetItem);
    const updatedArr = targetArr.filter((npu: any) => npu.title !== item.title);
    if (updatedArr.length === 0) {
      sessionStorage.removeItem('npuLogProgressItem');
    } else {
      sessionStorage.setItem('npuLogProgressItem', JSON.stringify(updatedArr));
    }
  }
  const timerItem = setTimeout(() => {
    percentValue.value = 0;
    percent.value = '0%';
    item.showProgress = false;
    item.isCollectingOk = false;
    item.isCollectingErr = false;
    item.down = false;
    item.progressResult = '';
  }, 3000);
  timer.push(timerItem);
}

// 获取数据
function getData() {
  globalStoreService.setValue('isLoading', true);

  // 获取npu日志数据
  getAllProcessor();
  if (multihost.value) {
    getAllHostLog();
  }

  // 获取PCLe、黑匣子功能、系统串口数据记录功能 数据
  systemDiagnostic()
    .then((data: any) => {
      systemInfo[0].status = data.BlackBoxEnabled;
      systemInfo[1].status = data.SerialPortDataEnabled;
      systemInfo[0].statusPCIe = data.PCIeInterfaceEnabled;
      systemInfo[0].statusSDIBlackBox = data.IsSupportBlackBoxOfSdi;
      if (!systemInfo[0].statusPCIe) {
        systemInfo[0].disable = true;
      }
      // 此处需要根据产品名称修改大小
      const blackBoxSize = Math.round(data.BlackBoxSize / (1024 * 1024));
      const serialDataSize = Math.round(data.SerialPortDataSize / (1024 * 1024));
      systemInfo[0].size = blackBoxSize + 'M';
      systemInfo[1].size = serialDataSize + 'M';
      systemInfo[1].desc = traduction('SYSTEM_LOG_SERIAL_PORT1', [serialDataSize]);
    })
    .finally(() => {
      globalStoreService.setValue('isLoading', false);
    });
}

onMounted(() => {
  getData();
  if (hostLogProgressUrl) {
    hostSecondEntry = true;
    let idx = hostLogCards.value.findIndex((v: hostItemT) => v.title === hostLogProgressItem.title);
    hostLogCards.value.splice(idx, 1, hostLogProgressItem);
    let item = hostLogCards.value[idx];
    taskService(hostLogProgressUrl, item);
  }
});

onUnmounted(() => {
  // 清空定时器
  timer.forEach((item: any) => {
    clearTimeout(item);
  });
});
</script>

<template>
  <div id="systemLog" class="system-log">
    <div class="boxs">
      <template v-for="item in systemInfo" :key="item.title">
        <div v-if="item.show" class="box">
          <el-form label-width="auto" label-position="left">
            <!-- PCIe接口 -->
            <el-form-item v-if="item.id === 'blackBox'" class="item-box" :label="item.titlePCIe">
              <el-switch
                :id="item.idPCIe"
                v-model="item.statusPCIe"
                :disabled="isSystemLock"
                @change="changePCIe(item)"
              />
            </el-form-item>

            <div v-if="item.id === 'blackBox' && !multihost" class="desc">{{ $t('SYSTEM_LOG_PCIE_DESCRIBE') }}</div>
            <div v-if="item.id === 'blackBox' && multihost" class="desc">{{ $t('SYSTEM_LOG_PCIE_DESCRIBE2') }}</div>

            <el-form-item v-if="item.id !== 'blackBox' || (!multihost && fdmSupport)" class="item-box" :label="item.title">
              <el-switch
                :id="item.id"
                v-model="item.status"
                :disabled="isSystemLock || item.disable"
                @change="change(item)"
              />
            </el-form-item>

            <div v-if="item.id !== 'blackBox' || (!multihost && fdmSupport)" class="desc">{{ item.desc }}</div>
          </el-form>
          <!-- 下载链接 -->
          <div v-if="item.id !== 'blackBox' || (!multihost && fdmSupport)" class="section up">
            <div class="left">
              <img class="file-img" src="@/assets/common/image/folder.svg" alt="" />
              <div class="name-size">
                <p class="name">{{ item.fileName }}</p>
                <p class="size">{{ item.size }}</p>
              </div>
            </div>

            <div class="right">
              <!-- 没有通过v-if或者v-show来控制显示，而是通过类名绑定设置visibility: hidden; 这样利用了按钮的宽度来对加载中的图标进行定位，
              否则加载中的位置不方便设置（毕竟小语种的文本宽度不同） -->
              <!-- 下载按钮 -->
              <el-button
                :id="item.id + 'Download'"
                :class="item.down ? 'visibility-hidden' : ''"
                @click="download(item)"
              >
                <el-icon>
                  <IconDownload />
                </el-icon>
                {{ $t('COMMON_DOWN') }}
              </el-button>
              <!-- 加载中 -->
              <div class="loading-box" :class="item.down ? '' : 'visibility-hidden'">
                <Loading :state="true" />
              </div>
            </div>
          </div>
          <!-- SDI黑匣子描述信息 -->
          <el-form
            v-if="item.id === 'blackBox' && item.statusSDIBlackBox"
            label-width="auto"
            label-position="left"
            class="sdi-sction"
          >
            <el-form-item class="item-box" :label="item.titleSDIBlackBox"></el-form-item>
            <div class="desc">{{ item.descSDIBlackBox }}</div>
          </el-form>
          <!-- SDI黑匣子下载链接 -->
          <div v-if="item.id === 'blackBox' && item.statusSDIBlackBox" class="section">
            <div class="left">
              <img class="file-img" src="@/assets/common/image/folder.svg" alt="" />

              <div class="name-size">
                <p class="name">{{ item.fileNameSDIBlackBox }}</p>
                <p class="size">{{ item.sizeSDIBlackBox }}</p>
              </div>
            </div>

            <div class="right">
              <!-- 没有通过v-if或者v-show来控制显示，而是通过类名绑定设置visibility: hidden; 这样利用了按钮的宽度来对加载中的图标进行定位，
              否则加载中的位置不方便设置（毕竟小语种的文本宽度不同） -->
              <!-- 下载按钮 -->
              <el-button
                :id="item.idSDIBlackBox + 'Download'"
                :class="item.downSDIBlackBox ? 'visibility-hidden' : ''"
                @click="sdiDownload(item)"
              >
                <el-icon>
                  <IconDownload />
                </el-icon>
                {{ $t('COMMON_DOWN') }}
              </el-button>
              <!-- 加载中 -->
              <div class="loading-box" :class="item.downSDIBlackBox ? '' : 'visibility-hidden'">
                <Loading :state="true" />
              </div>
            </div>
          </div>
        </div>
      </template>
      <!-- SDI黑匣子瞎子弹窗信息 -->
      <Dialog ref="dialogRef" :config="dialogConfig" @close="closeModal">
        <template v-if="dialogConfig.id === 'SDIBlackBoxTip'" #other>
          <div>
            <div class="sdi-dialog">
              <el-icon>
                <IconRemind />
              </el-icon>
              <div class="sdi-content">
                <p>{{ traduction('SYSTEM_SID_DOWN_TIP1') }}</p>
                <p>{{ traduction('SYSTEM_SID_DOWN_TIP2') }}</p>
                <p>{{ traduction('SYSTEM_SID_DOWN_TIP3') }}</p>
              </div>
            </div>
            <div class="sdi-info-tip">
              <p>{{ traduction('SYSTEM_SID_DOWN_TIP4') }}</p>
            </div>
          </div>
        </template>
      </Dialog>
    </div>
    <!-- 各个HOST的串口数据 -->
    <div v-if="hostLogCards.length" id="systemLogHost" class="npu">
      <div class="title">{{ $t('SYSTEM_LOG_SERIAL_PORT') }}</div>
      <div class="content">
        <div v-for="item in hostLogCards" :key="item.title" class="item">
          <div class="left">
            <img src="@/assets/common/image/folder.svg" class="folder" />
            <div class="file-info">
              <div class="file-name">{{ item.title }}</div>
              <div v-if="item.showProgress" class="progress">
                <el-progress
                  :percentage="item.hostPercentValue"
                  :format="progressFormat"
                  :status="item.progressResult"
                />
                <span class="percent">{{ item.hostPercent }}</span>
                <!-- 成功 -->
                <span v-if="item.isCollectingOk" class="download-res">
                  <el-icon>
                    <IconSuccess />
                  </el-icon>
                  <span>{{ $t('NPU_COMPLETED') }}</span>
                </span>
                <!-- 失败 -->
                <span v-if="item.isCollectingErr" class="download-res">
                  <el-icon>
                    <IconError />
                  </el-icon>
                  <span>{{ $t('NPU_COLLECTION_FAILED') }}</span>
                </span>
              </div>
            </div>
          </div>
          <!-- 下载 -->
          <div class="right">
            <el-button
              :id="item.title + 'Download'"
              :class="item.down ? 'visibility-hidden' : ''"
              @click="hostLogDownload(item)"
            >
              <el-icon>
                <IconDownload />
              </el-icon>
              {{ $t('COMMON_DOWN') }}
            </el-button>
            <div class="loading-box" :class="item.down ? '' : 'visibility-hidden'">
              <Loading :state="true" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="npuCards.length" id="systemLogNPU" class="npu">
      <div class="title">{{ $t('NPU_LOG') }}</div>
      <div class="sub-title">{{ $t('NPU_DESCRIPTION') }}</div>
      <div class="content">
        <div v-for="item in npuCards" :key="item.title" class="item">
          <div class="left">
            <img src="@/assets/common/image/folder.svg" class="folder" />
            <div class="file-info">
              <div class="file-name">{{ item.title }}</div>
              <div v-if="item.showProgress" class="progress">
                <el-progress
                  :percentage="item.percentValue"
                  :format="progressFormat"
                  :status="item.progressResult"
                />
                <span class="percent">{{ item.percent }}</span>
                <!-- 成功 -->
                <span v-if="item.isCollectingOk" class="download-res">
                  <el-icon>
                    <IconSuccess />
                  </el-icon>
                  <span>{{ $t('NPU_COMPLETED') }}</span>
                </span>
                <!-- 失败 -->
                <span v-if="item.isCollectingErr" class="download-res">
                  <el-icon>
                    <IconError />
                  </el-icon>
                  <span>{{ $t('NPU_COLLECTION_FAILED') }}</span>
                </span>
              </div>
            </div>
          </div>
          <!-- 下载 -->
          <div class="right">
            <el-button
              :id="item.title + 'Download'"
              :class="item.down ? 'visibility-hidden' : ''"
              @click="download(item)"
            >
              <el-icon>
                <IconDownload />
              </el-icon>
              {{ $t('COMMON_DOWN') }}
            </el-button>
            <div class="loading-box" :class="item.down ? '' : 'visibility-hidden'">
              <Loading :state="true" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- NPU弹窗1信息 -->
    <Dialog ref="npuTypeDialogRef" :config="npuTypeDialogConfig" @close="closeNPUTypeModal">
      <template #other>
        <div class="dialog-content">
          <div class="dialog-check-content">
            <div class="check-title">
              <div>{{ $t('NPU_TYPE_PROMPT') }}</div>
            </div>
            <div class="check-content">
              <el-checkbox
                id="check-all"
                class="dialog-check-box"
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                {{ $t('ALARM_EVENT_ALL') }}
              </el-checkbox>
              <el-checkbox-group
                v-model="npuType"
                @change="handleCheckTypeChange"
              >
                <el-checkbox v-for="npuItem in npuTypeList" :key="npuItem" :id="npuItem.value" :label="npuItem.label" :value="npuItem.value">
                  {{ $t(npuItem.label) }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
      </template>
    </Dialog>
    <!-- NPU弹窗信息 -->
    <Dialog ref="npuDialogRef" :config="npuDialogConfig" @close="closeNPUModal">
      <template #other>
        <div>
          <div class="sdi-dialog">
            <el-icon>
              <IconRemind />
            </el-icon>
            <div class="sdi-content">
              <p>{{ traduction('SYSTEM_NPU_DOWN_TIP1') }}</p>
              <p>{{ traduction('SYSTEM_NPU_DOWN_TIP2') }}</p>
              <p>{{ traduction('SYSTEM_NPU_DOWN_TIP3') }}</p>
            </div>
          </div>
          <div class="sdi-info-tip">
            <p>{{ traduction('SYSTEM_SID_DOWN_TIP4') }}</p>
          </div>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<style scoped lang="scss">
.system-log {
  font-size: 12px;
  color: var(--o-text-color-secondary);
  padding-right: 24px;

  .boxs {
    .box {
      margin-bottom: 16px;
      padding: 24px;
      border-radius: 4px;
      background-color: var(--o-bg-color-base);

      :deep(.el-form) {
        .el-form-item {
          margin-bottom: 0;

          .el-form-item__label-wrap {
            .el-form-item__label {
              font-weight: 600;
              color: var(--o-text-color-primary);
              font-size: 16px;
              line-height: 16px;
              padding-bottom: 8px;
            }
          }

          .el-form-item__content {
            line-height: 40px;
          }
        }

        .desc {
          color: rgba(141, 152, 170, 1);
          margin-bottom: 16px;
        }
      }

      .item-box {
        .row {
          margin-bottom: 8px;
          display: flex;
          align-items: center;

          .title {
            margin-right: 24px;
            font-weight: bold;
            color: var(--o-text-color-primary);
            font-size: 16px;
            line-height: 24px;
          }
        }

        .desc {
          margin-bottom: 16px;
          color: rgba(141, 152, 170, 1);
        }
      }

      .section {
        padding: 16px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 4px;
        background-color: var(--o-bg-color-light);
        &.up {
          margin-top: 8px;
        }
        .left {
          display: flex;
          align-items: center;

          .file-img {
            margin-right: 8px;
          }

          .name-size {
            .name {
              color: var(--o-text-color-primary);
              font-size: 16px;
            }

            .size {
              color: rgba(141, 152, 170, 1);
            }
          }
        }

        .el-icon {
          margin-right: 4px;
          font-size: 16px;
          cursor: pointer;
        }
      }
      .sdi-sction {
        margin-top: 12px;
      }
    }
  }

  .npu {
    padding: 24px;
    border-radius: 4px;
    background-color: var(--o-bg-color-base);

    .title {
      color: var(--o-text-color-primary);
      font-size: 16px;
      line-height: 24px;
      margin-bottom: 8px;
    }

    .sub-title {
      font-size: 12px;
      color: rgba(141, 152, 170, 1);
      line-height: 16px;
    }

    .item {
      margin-top: 16px;
      padding: 16px 24px;
      border-radius: 4px;
      background-color: var(--o-bg-color-light);
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;

        .folder {
          margin-right: 8px;
        }

        .file-info {
          .file-name {
            color: var(--o-text-color-primary);
            font-size: 16px;
          }
          .progress {
            display: flex;
            align-items: center;

            :deep(.el-progress) {
              width: 262px;
              margin-right: 8px;
              border-radius: 3px;
              background-color: var(--o-border-color-light);

              .el-progress__text {
                display: none;
              }
            }

            .download-res {
              display: flex;
              align-items: center;

              .el-icon {
                margin: 0 8px;
                font-size: 16px;
              }
            }
          }
        }
      }
    }
  }

  .right {
    position: relative;

    .loading-box {
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;

      :deep(.loading .circular) {
        margin-top: -10px;
        margin-left: -10px;
        height: 20px;
        width: 20px;
      }

      :deep(.loading) {
        background-color: rgba(0, 0, 0, 0);
      }
    }

    .visibility-hidden {
      visibility: hidden;
      pointer-events: none;
    }
  }
  .sdi-dialog {
    display: flex;
    line-height: 16px;
    padding: 8px 16px;
    border-radius: 4px;
    background-color: var(--o-color-state-primary-secondary);
    display: flex;

    .el-icon {
      margin-right: 12px;
      display: inline-block;
      width: 16px;
      height: 16px;
      color: rgba(0, 119, 255, 1); //icon不随品牌色变化
      font-size: 18px;
    }
  }
  .sdi-content {
    color: var(--el-color-black);
    margin-left: 0;
  }
  .sdi-info-tip {
    margin-top: 16px;
  }
}
#systemLogHost {
  .title {
    font-size: 16px;
    font-weight: 600;
  }
}
.dialog-content {
  .dialog-check-content {
    display: flex;
    .check-title {
      max-width: 110px;
      white-space: nowrap;
      margin-right: 24px;
      div {
        line-height: 32px;
        height: 32px;
      }
    }
    
    :deep(.el-checkbox__inner)::before{
      top: 3px;
      left: 3px;
    }
    .dialog-check-box {
      margin-right: 24px;
    }
    :deep(.el-checkbox-group){
      .el-checkbox{
        margin-right: 24px;
      }
      :nth-last-child(1){
        margin-right: 0;
      }
    }
  }
}
</style>
